package org.softwarepoets.emf.ecore.editor.extensions;

import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EGenericType;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EParameter;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.ui.PlatformUI;

public class CreateValidatorOperation extends AbstractExtensionAction {

	public CreateValidatorOperation() {
		super(EClass.class);
	}

	@Override
	public void run(IAction action) {
		InputDialog dialog = new InputDialog(
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
				"Enter Operation name",
				"Enter the name of the operation without parameters using valid java naming conventions.",
				"", new JavaNamingValidator());

		if (dialog.open() == InputDialog.OK) {
			EClass object = (EClass) element;
			EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(object);
			String name = dialog.getValue();
			EOperation eOper = EcoreFactory.eINSTANCE.createEOperation();
			eOper.setName(name);
			eOper.setEType(EcorePackage.Literals.EBOOLEAN);
			EParameter diagnostic = EcoreFactory.eINSTANCE.createEParameter();
			diagnostic.setName("diagnostic");
			diagnostic.setEType(EcorePackage.Literals.EDIAGNOSTIC_CHAIN);
			EParameter context = EcoreFactory.eINSTANCE.createEParameter();
			context.setName("context");
			context.setEType(EcorePackage.Literals.EMAP);
			EGenericType type1 = EcoreFactory.eINSTANCE.createEGenericType();
			type1.setEClassifier(EcorePackage.Literals.EJAVA_OBJECT);
			EGenericType type2 = EcoreFactory.eINSTANCE.createEGenericType();
			type2.setEClassifier(EcorePackage.Literals.EJAVA_OBJECT);
			context.getEGenericType().getETypeArguments().add(type1);
			context.getEGenericType().getETypeArguments().add(type2);
			eOper.getEParameters().add(diagnostic);
			eOper.getEParameters().add(context);
			Command cmd = AddCommand.create(editingDomain, object, null, eOper);
			editingDomain.getCommandStack().execute(cmd);
		}
	}
}

